#include "ClipManager.h"

ClipManager::ClipManager(void)
{
}

ClipManager::~ClipManager(void)
{
}

ClipManager ClipManager::getInstance(void)
{
	static ClipManager instance;
	return instance;
}

void ClipManager::destroy(void)
{
	while(!mIdleClips.empty())
	{
		delete mIdleClips.back();
		mIdleClips.pop_back();
	}
	while(!mMainClips.empty())
	{
		delete mMainClips.back();
		mMainClips.pop_back();
	}
}

bool ClipManager::loadFromFile(const std::string& file)
{
	TiXmlDocument* pDoc = new TiXmlDocument();
	if(!pDoc->LoadFile(file.c_str()))
	{
		return false;
	}

	std::string elementName;
	for(TiXmlElement* pElement = pDoc->FirstChildElement(); pElement != NULL; pElement = pElement->NextSiblingElement())
	{
		elementName = pElement->Value();
		if(elementName.compare("video") == 0)
		{
			TiXmlAttribute* pAttribute = pElement->FirstAttribute();
			mVideo = pAttribute->Value();

			pElement = pElement->FirstChildElement();
			elementName = pElement->Value();
		}
		if(elementName.compare("clip") == 0)
		{
			std::string name;
			double begin = -1;
			double end = -1;
			CLIP_TYPE type = TYPE_IDLE;

			for(TiXmlAttribute* pAttribute = pElement->FirstAttribute(); pAttribute != NULL; pAttribute = pAttribute->Next())
			{
				elementName = pAttribute->Name();
				if(elementName.compare("name") == 0)
				{
					name = pAttribute->Value();
				}
				else if(elementName.compare("begin") == 0)
				{
					begin = atof(pAttribute->Value());
				}
				else if(elementName.compare("end") == 0)
				{
					end = atof(pAttribute->Value());
				}
				else if(elementName.compare("type") == 0)
				{
					type = (CLIP_TYPE)atoi(pAttribute->Value());
				}
			}

			Clip* pClip = new Clip(name,begin,end,type);
			registerClip(pClip, type);
		}
	}

	return true;
}

void ClipManager::registerClip(Clip* pClip, CLIP_TYPE type)
{
	if(type == TYPE_IDLE)
	{
		mIdleClips.push_back(pClip);
	}
	else
	{
		mMainClips.push_back(pClip);
	}
}

Clip* ClipManager::retrieveClip(const std::string& name, CLIP_TYPE type)
{
	std::vector<Clip*>::iterator i;
	std::vector<Clip*>::iterator end;

	if(type == 0)
	{
		i = mIdleClips.begin();
		end = mIdleClips.end();
	}
	else
	{
		i = mMainClips.begin();
		end = mMainClips.end();
	}

	for(i; i != end; ++i)
	{
		if((*i)->mName.compare(name) == 0)
			return (*i);
	}

	return NULL;
}

Clip* ClipManager::retrieveIdleClip(void)
{
	int i = rand() % mIdleClips.size();
	return mIdleClips.at(i);
}

const std::string& ClipManager::getVideoFilename(void)
{
	return mVideo;
}